/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui; 

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.ui.base.BaseActivity;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.BSUPrivate;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.FractionalTouchDelegate;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * An activity that shows the personal information for a student's neighbor. Activity that is started when a user selects a 
 * neighbor from the list on the {@link HousingInfoActivity}.
 * @author Kyle Parker, University Computing Services
 */
public class NeighborActivity extends BaseActivity { 
    private static final String TAG = "NeighborActivity";

    private View mLoadingSpinner;
    private Activity mActivity;
    private Person mPerson;
    private BroadcastReceiver mReceiver;
    private CompoundButton mStarred;

    private String mBSUID;
    private String mPersonBSUID;
    private String mPersonTypeID;
    private boolean mLogin;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_neighbor_info);
		
        getActivityHelper().setupActionBar(false, "My Home | Neighbor Info");        
        mActivity = this;
        
        handleLogout();    
        handleLogin();

        mLoadingSpinner = findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);	
        
        mStarred = (CompoundButton) findViewById(R.id.star_button);
        mStarred.setFocusable(true);
        mStarred.setClickable(true);
        
        // Larger target triggers star toggle
        final View starParent = findViewById(R.id.name);
        FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f));
    	
        getExtras();

		// Hide the neighbor while the data is loading
        hideNeighbor();
        if (mLogin) {
        	loadNeighbor();
        }

        AnalyticsUtils.getInstance(mActivity).trackPageView("/Neighbor");
    }
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }
    
    /**
     * Get the extras from the Intent
     */
    public void getExtras() {
		Bundle extras = getIntent().getExtras(); 

		if (extras != null) {
			if (extras.getString(Constants.EXTRA_BSU_ID) != null) {
				mPersonBSUID = extras.getString(Constants.EXTRA_BSU_ID);
			}
			if (extras.getString(Constants.EXTRA_PERSON_TYPE_ID) != null) {
				mPersonTypeID = extras.getString(Constants.EXTRA_PERSON_TYPE_ID);
			}
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the neighbor information from the service handler
     */
    private void loadNeighbor() {		
        Runnable load = new Runnable(){
            public void run() { 
            	try {
            		// Retrieve the employee information if the neighbor is a hall director
	            	if (Integer.parseInt(mPersonTypeID) == Constants.VALUE_PERSON_TYPE_DIRECTOR) {
	            		PersonData.initializePerson(mPersonBSUID, Constants.QUERY_PERSON_DIRECTORY_FACULTY, mActivity);
	            	} else {
	            		PersonData.initializePerson(mPersonBSUID, Constants.QUERY_PERSON_DIRECTORY_STUDENT, mActivity);
	            	}
	            	
	                if (PersonData.getPersonCount() > 0) {
	                	// This will return 1 person record - retrieve the information from the first position
	                	mPerson = PersonData.getPerson(0);
                    }
	    	    	
	        		mActivity.runOnUiThread(returnNeighbor);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadNeighbor");
        thread.start();
    }
    
    /**
     * Load the neighbor (roommates and floormates) info from the service handler and set the visibility of the spinner to "gone"
     */
    private Runnable returnNeighbor= new Runnable(){
        public void run() {
        	displayNeighbor();
            mLoadingSpinner.setVisibility(View.GONE);
        }
    };
    
    /**
     * Display the neighbor information and set the starred status
     */
    private void displayNeighbor() { 
    	if (mPerson != null) {
    		RelativeLayout view = (RelativeLayout) findViewById(R.id.neighbor_info_container);
            view.setVisibility(View.VISIBLE);
        	view.setBackgroundResource(R.color.content_background);
            
        	String name;
        	String title;
        	
        	if (Integer.parseInt(mPersonTypeID) == Constants.VALUE_PERSON_TYPE_DIRECTOR) {
        		view.findViewById(R.id.address).setVisibility(View.GONE);
	            
        		name = (mPerson.getNamePrefix() + " " + mPerson.getFirstName() + " " + mPerson.getLastName() + " " + mPerson.getNameSuffix()).trim();
	    		title = mPerson.getTitleRank();

	    		if (mPerson.getDepartment().length() > 0 && !mPerson.getDepartment().contains(BSUPrivate.VALUE_NO_DEPARTMENT)) {
	    			title = title + ", " + mPerson.getDepartment();
	    		}
        	} else {
        		name = (mPerson.getFirstName() + " " + mPerson.getLastName() + " " + mPerson.getNameSuffix()).trim();
	    		String address = UIUtils.formatAddress(mPerson.getAddress1(), mPerson.getAddress2(), mPerson.getCity(), 
	    				mPerson.getState(), mPerson.getZip());

	        	//view.findViewById(R.id.address).setVisibility(View.GONE);

	        	switch (Integer.parseInt(mPersonTypeID)) {
		        	case Constants.VALUE_PERSON_TYPE_ROOMMATE:
		        		title = "Roommate";
		        		break;
		        	case Constants.VALUE_PERSON_TYPE_RA:
		        		title = "Resident Assistant (RA)";
		        		break;
		        	default:
		        		title = "Floormate";
		        		break;
	        	}

	    		UIUtils.displayTextView(view, R.id.address, address);
        	}
    		
	        boolean starred = PersonData.getPersonStarred(mActivity, mBSUID, mPersonBSUID);
	        
            // Unregister around setting checked state to avoid triggering
            // listener since change isn't user generated.
            mStarred.setOnCheckedChangeListener(null);
            mStarred.setChecked(starred);
            mStarred.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			    	PersonData.starPerson(mActivity, mPerson.getFirstName(), mPerson.getLastName(), mPerson.getNameSuffix(), isChecked, 
			    			mBSUID, mPersonBSUID, Integer.parseInt(mPersonTypeID));
			    }           	
            });

    		UIUtils.displayTextView(view, R.id.name, name);
    		UIUtils.displayTextView(view, R.id.title, title);
    		UIUtils.displayTextView(view, R.id.email, mPerson.getEmailAddress());
    		UIUtils.displayTextView(view, R.id.phone, mPerson.getPhone());	
        } else {
        	hideNeighbor();
    	}
    }

    /**
     * Hide the neighbor view during the load process or if the neighbor object is empty
     */
	private void hideNeighbor() { 
		RelativeLayout view = (RelativeLayout) findViewById(R.id.neighbor_info_container);
        view.setVisibility(View.GONE);			
        view.setBackgroundResource(R.drawable.empty_people_background); 
	}

    /**
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
    		mBSUID = person.getBSUID();
        	mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	}    	
    }
}
